#include <kmpkg/base/downloads.h>
#include <kmpkg/base/files.h>

#include <kmpkg/archives.h>
#include <kmpkg/commands.bootstrap-standalone.h>
#include <kmpkg/configure-environment.h>
#include <kmpkg/tools.h>
#include <kmpkg/kmpkgcmdarguments.h>

#include <string>

namespace kmpkg
{
    constexpr CommandMetadata CommandBootstrapStandaloneMetadata{
        "bootstrap-standalone",
        msgCmdBootstrapStandaloneSynopsis,
        {"kmpkg bootstrap-standalone"},
        Undocumented,
        AutocompletePriority::Never,
        0,
        0,
        {},
        nullptr,
    };

    void command_bootstrap_standalone_and_exit(const KmpkgCmdArguments& args, const Filesystem& fs)
    {
        (void)args.parse_arguments(CommandBootstrapStandaloneMetadata);

        DownloadManager download_manager{{}};
        const auto maybe_kmpkg_root_env = args.kmpkg_root_dir_env.get();
        if (!maybe_kmpkg_root_env)
        {
            Checks::msg_exit_with_message(KMPKG_LINE_INFO, msgKmpkgRootRequired);
        }

        const auto kmpkg_root = fs.almost_canonical(*maybe_kmpkg_root_env, KMPKG_LINE_INFO);
        fs.create_directories(kmpkg_root, KMPKG_LINE_INFO);
        auto tarball =
            download_kmpkg_standalone_bundle(download_manager, fs, kmpkg_root).value_or_exit(KMPKG_LINE_INFO);
        fs.remove_all(kmpkg_root / "kmpkg-artifacts", KMPKG_LINE_INFO);
        extract_tar(find_system_tar(fs).value_or_exit(KMPKG_LINE_INFO), tarball, kmpkg_root);
        fs.remove(tarball, KMPKG_LINE_INFO);
        Checks::exit_success(KMPKG_LINE_INFO);
    }
}
